<?php

namespace app\common\validate\tyyh;

class Collect extends Base
{
	/**
     * 验证规则
     */
    protected $rule = [
        'lock'                => 'require',
        'id'                  => 'require',
        'ids'                 => 'require|isUsers:tyyh\\Collect',
        'uid'                 => 'require',
        'pid'                 => 'require|isCollect|isCollected'
    ];


    /**
     * 提示消息
     */
    protected $message = [
        'lock.require'                  => '验证场景不存在',
        'id.require'                    => '收藏夹ID不能为空',
        'uid.require'                   => '用户ID不能为空',
        'pid.require'                   => '产品ID不能为空',
        'pid.isCollect'                 => '产品已下架',
        'pid.isCollected'               => '您已经收藏了该产品'
    ];
    /**
     * 验证场景
     */
    protected $scene = [
        'save'      => [
        	'id' => 'isUser:tyyh\\Collect',
        	'uid',
        	'pid'
        ],
        'private'   => ['uid'],
        'del'       => ['id', 'uid'],
        'dels'      => ['ids', 'uid']
    ];

    //验证数据审核是否已经完成
    protected function isCollect($value, $rule, $data = []) {
        $data = loadOnly('Model')->find('tysj\\Product', $value);
        $enum = loadEnum('ProductStatus');
        if(empty($data) || $data['status'] != $enum->code2key('shangjia')) {
        	return false;
        } else {
        	return true;
        }
    }

    //验证是否已经收藏了该产品
    protected function isCollected($value, $rule, $data = []) {
    	$model = loadModel('tyyh\\Collect');
    	$model->where(['uid' => $data['uid'], 'pid' => $data['pid']]);
    	if(isset($data['id'])) {
    		$model->where('id', '<>', $data['id']);
    	}
    	$row = $model->find();
    	return empty($row);
    }
}